package com.chenbei.handler;

import cn.dev33.satoken.stp.StpInterface;
import com.chenbei.system.domain.SysMenu;
import com.chenbei.system.domain.SysRole;
import com.chenbei.system.enums.SysMenuTypeEnum;
import com.chenbei.system.service.ISysRoleMenuService;
import com.chenbei.system.service.ISysUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
@Service
@Slf4j
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Autowired
    private ISysRoleMenuService sysRoleMenuService;

    /**
     * 获取权限列表集合
     * @param loginId 登录用户ID
     * @param loginType 登录类型
     * @return List
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        if (loginId != null) {
            long loginUserId = Long.parseLong(loginId.toString());
            List<SysRole> sysRoles = sysUserRoleService.listByAdminUserId(loginUserId);
            if (sysRoles != null && !sysRoles.isEmpty()) {
                List<Long> roleIds = sysRoles.stream().map(SysRole::getId).collect(Collectors.toList());
                List<SysMenu> sysMenus = sysRoleMenuService.listByRoleId(roleIds);
                if (sysMenus != null && !sysMenus.isEmpty()) {
                    return sysMenus.stream().filter(sysMenu -> Objects.equals(sysMenu.getType(), SysMenuTypeEnum.BUTTON.getType())).map(SysMenu::getPermission).collect(Collectors.toList());
                }
            }
        }
        return null;
    }

    /**
     * 获取角色类型
     * @param loginId 登录用户ID
     * @param loginType 登录用户类型
     * @return List
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        if (loginId != null) {
            long loginUserId = Long.parseLong(loginId.toString());
            List<SysRole> sysRoles = sysUserRoleService.listByAdminUserId(loginUserId);
            if (sysRoles != null && !sysRoles.isEmpty()) {
                log.info("角色列表:{}", sysRoles.stream().map(SysRole::getCode).collect(Collectors.toList()));
                return sysRoles.stream().map(SysRole::getCode).collect(Collectors.toList());
            }
        }
        return null;
    }
}
